<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <!-- 搜索展示区域 -->
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input placeholder="请输入角色ID" v-model="roleId" clearable @clear="getRoleList">
                        <el-button slot="append" icon="el-icon-search" @click="getRoleListById"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表展示区域 -->
            <el-table :data="roleList" stripe border>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row
                            :class="['bdbottom',i1===0?'bdtop':'','vcenter']"
                            v-for="(item,i1) in scope.row.children"
                            :key="item.id"
                        >
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag
                                    @close="removeRightById(scope.row,item.id)"
                                    closable
                                >{{item.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二三级权限 -->
                            <el-col :span="19">
                                <el-row
                                    :class="[i2===0?'':'bdtop']"
                                    v-for="(item2,i2) in item.children"
                                    :key="item2.id"
                                >
                                    <el-col :span="6">
                                        <el-tag
                                            @close="removeRightById(scope.row,item2.id)"
                                            type="success"
                                            closable
                                        >{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag
                                            @close="removeRightById(scope.row,item3.id)"
                                            closable
                                            type="warning"
                                            v-for="(item3,i3) in item2.children"
                                            :key="item3.id"
                                        >{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="primary"
                            icon="el-icon-edit"
                            @click="showEditRoles(scope.row)"
                        >编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-edit" @click="delRoles(scope.row.id)">删除</el-button>
                        <el-button
                            size="mini"
                            type="warning"
                            icon="el-icon-edit"
                            @click="getRoleTreeList(scope.row)"
                        >分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 添加角色dialog对话框 -->
            <el-dialog
                title="添加角色"
                :visible.sync="addRoleDialogVisible"
                width="50%"
                @close="addFormClose"
            >
                <el-form
                    ref="addRoleFormRef"
                    :model="addForm"
                    :rules="addFormRules"
                    label-width="80px"
                >
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="addForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="resetAddForm">取 消</el-button>
                    <el-button type="primary" @click="addRoleForm">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 分配角色对话框 -->
            <el-dialog
                title="分配权限"
                :visible.sync="setRightDialogVisible"
                width="50%"
                @close="setRightDialogClose"
            >
                <el-tree
                    :data="rightList"
                    :props="treeProps"
                    ref="setFormRef"
                    show-checkbox
                    default-expand-all
                    node-key="id"
                    :default-checked-keys="checkedKeys"
                ></el-tree>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="setRightDialogVisible=false">取 消</el-button>
                    <el-button type="primary" @click="saveRights">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 编辑角色对话框 -->
            <el-dialog
                title="编辑角色"
                :visible.sync="updateRolesDialogVisible"
                width="50%"
                @close="EditClose"
            >
                <el-form
                    :model="roleInfo"
                    :rules="editRules"
                    ref="editRoleForm"
                    label-width="100px"
                >
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="roleInfo.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="roleInfo.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="updateRolesDialogVisible=false">取 消</el-button>
                    <el-button type="primary" @click="saveRoles">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
            roleList: [],
            rightList: [],
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            checkedKeys: [],
            roleId: '',
            setRoleId: '',
            addRoleDialogVisible: false,
            setRightDialogVisible: false,
            updateRolesDialogVisible: false,
            addForm: {
                roleName: '',
                roleDesc: ''
            },
            addFormRules: {
                roleName: [
                    {
                        required: true,
                        message: '请输入角色名称',
                        trigger: 'blur'
                    },
                    {
                        max: 10,
                        message: '不能超过10个字符',
                        trigger: 'blur'
                    }
                ],
                roleDesc: [
                    {
                        required: true,
                        message: '请输入角色描述',
                        trigger: 'blur'
                    },
                    {
                        max: 20,
                        message: '不能超过20个字符',
                        trigger: 'blur'
                    }
                ]
            },
            editRules: {
                roleName: [
                    {
                        required: true,
                        message: '请输入角色名称',
                        trigger: 'blur'
                    },
                    {
                        max: 10,
                        message: '不能超过10个字符',
                        trigger: 'blur'
                    }
                ],
                roleDesc: [
                    {
                        required: true,
                        message: '请输入角色描述',
                        trigger: 'blur'
                    },
                    {
                        max: 20,
                        message: '不能超过20个字符',
                        trigger: 'blur'
                    }
                ]
            },
            roleInfo: {}
        }
    },
    created() {
        this.getRoleList()
    },
    methods: {
        async getRoleList() {
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) {
                return this.$message.error('角色列表获取失败')
            }
            this.roleList = res.data
            //console.log(res)
        },
        async getRoleListById() {
            //根据角色id进行角色查找
            const { data: res } = await this.$http.get(`roles/${this.roleId}`)
            if (res.meta.status !== 200) return this.$message.error('查询失败')
            this.roleList = []
            //这个时候应该用push，因为得到的是一个对象而不是数组
            this.roleList.push(res.data)
        },
        addRoleForm() {
            this.$refs.addRoleFormRef.validate(async (valid) => {
                if (!valid) {
                    return this.$message.error('请完善表格中的信息')
                }
                const { data: res } = await this.$http.post('/roles', {
                    roleName: this.addForm.roleName,
                    roleDesc: this.addForm.roleDesc
                })
                if (res.meta.status !== 201) {
                    return this.$message.error('创建角色失败')
                }
                this.getRoleList()
                this.$message.success(res.meta.msg)
                this.addRoleDialogVisible = false
                this.$refs.addRoleFormRef.resetFields()
            })
        },
        resetAddForm() {
            this.$refs.addRoleFormRef.resetFields()
            this.addRoleDialogVisible = false
        },
        addFormClose() {
            this.$refs.addRoleFormRef.resetFields()
        },
        async removeRightById(role, id) {
            const confirmResult = await this.$confirm(
                '此操作会删除该权限, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch((err) => {
                // this.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // })
                // console.log('catch')
                err
            })
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res } = await this.$http.delete(
                `roles/${role.id}/rights/${id}`
            )
            if (res.meta.status !== 200) {
                return this.$message.error('删除权限失败')
            }
            //只进行部分更新，保持页面状态
            role.children = res.data
        },
        async getRoleTreeList(role) {
            //将正在操作的表单的id值保存起来，便于进行保存设置
            this.setRoleId = role.id
            const { data: res } = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) return this.$message.error('查询失败')
            this.rightList = res.data
            this.getChekcedKeys(role, this.checkedKeys)
            this.setRightDialogVisible = true
            // console.log(this.rightList)
        },
        getChekcedKeys(node, arr) {
            //没有children说明是最后一级，直接保存到数组里面
            if (!node.children) {
                return arr.push(node.id)
            }
            //递归调用，不断寻找第三级节点,然后将结果放到数组中
            node.children.forEach((element) => {
                this.getChekcedKeys(element, arr)
            })
        },
        setRightDialogClose() {
            //当关闭对话框的时候调用此方法，清空默认选中数组，避免多次渲染
            this.checkedKeys = []
        },
        //保存修改的权限
        async saveRights() {
            //获取选中和半选中的内容
            const keys = [
                ...this.$refs.setFormRef.getCheckedKeys(),
                ...this.$refs.setFormRef.getHalfCheckedNodes()
            ]
            // console.log(keys)
            // 将数组转换成字符串，数据间用逗号隔开
            const keysStr = keys.join(',')
            //将权限保存
            const { data: res } = await this.$http.post(
                `roles/${this.setRoleId}/rights`,
                {
                    rids: keysStr
                }
            )
            // console.log(this.setRoleId)
            // console.log(keysStr)
            // console.log(res)
            if (res.meta.status !== 200) {
                return this.$message.error('权限分配失败')
            }
            this.$message.success('权限分配成功')
            //刷新页面
            this.getRoleList()
            // console.log(this.roleList)
            this.setRightDialogVisible = false
        },
        showEditRoles(roleInfo) {
            this.roleInfo = roleInfo
            this.updateRolesDialogVisible = true
        },
        saveRoles() {
            this.$refs.editRoleForm.validate(async (valid) => {
                if (!valid) {
                    this.$message.error('请填写规范信息')
                }
                const { data: res } = await this.$http.put(
                    `roles/${this.roleInfo.id}`,
                    {
                        roleName: this.roleInfo.roleName,
                        roleDesc: this.roleInfo.roleDesc
                    }
                )
                if(res.meta.status!==200){
                    return this.$message.error('编辑失败')
                }
                this.$message.success('编辑成功')
                this.getRoleList()
                this.updateRolesDialogVisible=false
            })
        },
        EditClose() {
            this.$refs.editRoleForm.resetFields()
        },
        async delRoles(id){
            const confirm = await this.$confirm(
                '此操作将永久删除该角色, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch((err) => {
                this.$message.info('取消删除')
            })
            if (confirm === 'confirm') {
                const { data: res } = await this.$http.delete('roles/' + id)
                if (res.meta.status !== 200) {
                    this.$message.error('删除失败')
                }
                this.$message({
                    type: 'success',
                    message: res.meta.msg
                })
                this.getRoleList()
            }
        }
    }
}
</script>

<style lang='less' scoped>
.el-tag {
    margin: 10px;
}
.bdbottom {
    border-bottom: 1px solid #ccc;
}
.bdtop {
    border-top: 1px solid #ccc;
}
.vcenter {
    display: flex;
    align-items: center;
}
</style>